package com.alex.controller;

import com.alex.client.HttpClient;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.nio.charset.StandardCharsets;


@RestController
//@Api(tags = "下载NBIB")
@RequestMapping("/download")
@SuppressWarnings("ALL")
public class DownloadController {
    @GetMapping("download")

    public void download(Integer pmid, HttpServletResponse response) throws Exception {
        byte[] bytes = new byte[1024];
        String nbibFromPubmed = HttpClient.getNbibFromPubmed("" + pmid);
        bytes = nbibFromPubmed.getBytes("UTF-8");
        String fileName = System.currentTimeMillis() + "_" + pmid + ".nbib";
        response.reset();
        response.setContentType("application/octet-stream;charset=utf-8");
        //导出文件中文名称
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
        response.addHeader("Content-Length", "" + bytes.length);
        OutputStream toClient;
        try {
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(bytes);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
